package cn.lxb.netstatagent;

import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Pattern;

/**
 * 先判断有无,再异步写文件或远程地址.
 * @author liuxianbo
 */
public class AddressRecordService {
	public static Set<String> addresses = new CopyOnWriteArraySet<>();
	public static BlockingQueue<String> addressQueue = new LinkedBlockingQueue<>();
	public static String recordType = System.getProperty("netstat-agent.record-type");
	static Pattern ignorePattern;	
	public static AddressRecorder recorder;

	static {
		startRecordThread();
		if ("collector".equalsIgnoreCase(recordType)) {
			recorder = new CollectorRecorder();
		} else {
			recorder = new FileRecorder();
		}
		
		String ignorePatternStr = System.getProperty("netstat-agent.ignore-pattern");
		if(ignorePatternStr!=null) {
			ignorePattern = Pattern.compile(ignorePatternStr.trim());
		}
	}

	public static void record(String address) {
		if (addresses.contains(address)) {
			LogUtil.debug("目标地址已经存在:" + address);
			return;
		}
		if (ignorePattern!=null && ignorePattern.matcher(address).matches()) {
			LogUtil.debug("目标地址被忽略:" + address);
			return;
		}
		addresses.add(address);
		addressQueue.add(address);
	}

	public static void startRecordThread() {
		Thread recordThread = new Thread(() -> {
			while (true) {
				try {
					String address = addressQueue.take();
					LogUtil.info("处理新增的地址: " + address);
					recorder.record(address);
				} catch (InterruptedException e) {
					break;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		recordThread.setName("netstat-agent-record-thread");
		recordThread.setDaemon(true);
		recordThread.start();
	}

}
